<template>
  <div>
    <van-nav-bar title="登录" />
    <van-form @submit="onSubmit">
      <van-field
        v-model="info.mobile"
        label="手机号"
        placeholder="请输入手机号"
        :rules="rules.mobile"
      />
      <van-field
        v-model="info.code"
        label="验证码"
        placeholder="请输入验证码"
        :rules="rules.code"
      />
      <div style="margin: 16px">
        <van-button
          :loading="isLoading"
          loading-text="loading..."
          round
          block
          type="info"
          native-type="submit"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginAPI } from '@/api/user'
export default {
  name: 'MyLogin',
  data () {
    return {
      isLoading: false,
      info: {
        mobile: '13877889999',
        code: '246810'
      },
      rules: {
        mobile: [
          { required: true, message: '请填写用户名' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
        ],
        code: [
          { required: true, message: '请填写验证码' },
          { pattern: /^\d{6}$/, message: '验证码为6位数字' }
        ]
      }
    }
  },
  methods: {
    async onSubmit () {
      // const res = await loginAPI({
      //   mobile: this.info.mobile,
      //   code: this.info.code
      // })
      // 以上代码可简化为：
      try {
        this.isLoading = true
        const res = await loginAPI(this.info)
        this.$store.commit('user/setToken', res.data)
        this.$toast.success('登录成功')
        if (this.$route.query.back) {
          this.$router.push(this.$route.query.back)
        } else {
          this.$router.push('/')
        }
      } catch {
        this.$toast.fail('登录失败')
      } finally {
        this.isLoading = false
      }
    }
  }
}
</script>

<style scoped></style>
